<template>
  <div class="chat-content" id="content">
    <!-- 使用新的MessageList组件 -->
    <MessageList
      ref="messageListRef"
      :messages="recordContent"
      :loading="loading"
      :end-flag="endFlag"
      :is-single-chat="isSingleChat"
      :message-handler-flag="messageHandlerFlag"
      :playing-voice-id="playingVoiceId"
      :default-avatar="defaultAvatar"
      @message-enter="$emit('message-enter', $event)"
      @message-leave="$emit('message-leave')"
      @avatar-click="$emit('avatar-click', $event)"
      @command="$emit('command', $event)"
      @get-content="$emit('get-content', $event)"
      @dropdown-close="$emit('dropdown-close')"
      @play-voice="$emit('play-voice', $event)"
      @download-file="$emit('download-file', $event)"
      @open-app-link="$emit('open-app-link', $event)"
      @resend="$emit('resend', $event)"
      @send-friend-check="$emit('send-friend-check', $event)"
      @edit="$emit('edit', $event)"
      @scroll="$emit('scroll', $event)"
                      />
                    </div>
</template>

<script>
import MessageList from './MessageList.vue';

export default {
  name: 'ChatContent',
  components: {
    MessageList,
  },
  data() {
    return {
      messageHandlerFlag: null,
      defaultAvatar: '/src/assets/icon/default-avatar.svg'
    };
  },
  computed: {
    // 缓存store状态，避免重复访问
    chatState() {
      return this.$store.state.chat;
    },
    
    // 从Vuex获取消息数据
    recordContent() {
      const { currentChatId } = this.chatState;
      if (currentChatId) {
        return this.$store.getters["chat/getMessages"](currentChatId);
      }
      return [];
    },
    
    // 加载状态
    loading() {
      return this.chatState.loading;
    },
    
    // 是否到达顶部
    endFlag() {
      return this.chatState.endFlag;
    },
    
    // 当前播放的语音ID
    playingVoiceId() {
      return this.chatState.playingVoiceId;
    },
    
    // 当前聊天ID
    currentChatId() {
      return this.chatState.currentChatId;
    },
    
    // 当前聊天信息
    currentChat() {
      return this.chatState.currentChat;
    },
    
    // 判断是否为单聊
    isSingleChat() {
      return this.currentChat && this.currentChat.type === 1;
    }
  },
  methods: {

    // 加载单聊消息
    async userChatMessages(friendId) {
      try {
        console.log('ChatContent userChatMessages called with friendId:', friendId);
        // 设置当前聊天ID
        this.$store.commit('chat/SET_CURRENT_CHAT_ID', friendId);
        // 使用Vuex store加载消息
        await this.$store.dispatch('chat/loadChatMessages', {
          chatId: friendId,
          chatType: 'single',
          page: 1,
          size: 50
        });
      } catch (error) {
        console.error('加载单聊消息失败:', error);
      }
    },

    // 加载群聊消息
    async userGroupChatMessages(groupChatId) {
      try {
        console.log('ChatContent userGroupChatMessages called with groupChatId:', groupChatId);
        // 设置当前聊天ID
        this.$store.commit('chat/SET_CURRENT_CHAT_ID', groupChatId);
        // 使用Vuex store加载消息
        await this.$store.dispatch('chat/loadChatMessages', {
          chatId: groupChatId,
          chatType: 'group',
          page: 1,
          size: 50
        });
      } catch (error) {
        console.error('加载群聊消息失败:', error);
      }
    },

    // 懒加载更多消息
    async lazyUserChatMessages() {
      try {
        const chatId = this.currentChatId;
        if (!chatId) {
          console.warn('懒加载消息失败: 没有当前聊天ID');
        return;
      }

        const chatType = this.isSingleChat ? 'single' : 'group';
        const currentMessages = this.recordContent;
        const page = Math.floor(currentMessages.length / 50) + 1;

        // 防止重复加载
        if (this.loading) {
          console.log('正在加载中，跳过懒加载');
          return;
        }

        await this.$store.dispatch('chat/loadChatMessages', {
          chatId,
          chatType,
          page,
          size: 50
        });
      } catch (error) {
        console.error('懒加载消息失败:', error);
        // 可以添加用户友好的错误提示
        this.$message?.error('加载更多消息失败，请重试');
      }
    },

    // 更新消息状态
    updateMessageStatus(tempId, status) {
      try {
        this.$store.commit('chat/UPDATE_MESSAGE_STATUS', { tempId, status });
      } catch (error) {
        console.error('更新消息状态失败:', error);
      }
    },

    // 错误处理
    handleError(error, context = '操作') {
      console.error(`${context}失败:`, error);
      this.$message?.error(`${context}失败，请重试`);
    },

    // ==================== WebSocket事件中心管理 ====================
    
    // 初始化WebSocket事件中心
    initWebSocketEventCenter() {
      // 导入WebSocket事件中心
      import('@/services/WebSocketEventCenter').then(({ webSocketEventCenter }) => {
        this.webSocketEventCenter = webSocketEventCenter;
        console.log('WebSocket事件中心已初始化');
      }).catch(error => {
        console.error('WebSocket事件中心初始化失败:', error);
      });
    },

    // 销毁WebSocket事件中心
    destroyWebSocketEventCenter() {
      if (this.webSocketEventCenter) {
        this.webSocketEventCenter.destroy();
        this.webSocketEventCenter = null;
      }
    },

    // 滚动到底部
    scrollToBottom() {
      console.log('ChatContent: 调用滚动到底部');
      // 使用nextTick确保DOM更新完成
      this.$nextTick(() => {
        // 通过ref调用MessageList组件的强制滚动方法
        if (this.$refs.messageListRef) {
          console.log('ChatContent: 找到MessageList引用，调用forceScrollToBottom');
          this.$refs.messageListRef.forceScrollToBottom();
        } else {
          console.log('ChatContent: 未找到MessageList引用，延迟重试');
          // 如果组件还没有挂载，延迟重试
          setTimeout(() => {
            this.scrollToBottom();
          }, 100);
        }
      });
    },

    // 隐藏浮动窗口
    hideFloatWindow(event) {
      // 可以在这里添加隐藏浮动窗口的逻辑
      this.messageHandlerFlag = null;
    }
  },

  // ==================== 生命周期钩子 ====================
  
  mounted() {
    // 初始化WebSocket事件中心
    this.initWebSocketEventCenter();
    
    // 监听Vuex状态变化，实现自动滚动
    this.unwatchScroll = this.$store.watch(
      (state) => state.chat.shouldScroll,
      (shouldScroll) => {
        console.log('ChatContent: Vuex shouldScroll状态变化', shouldScroll);
        if (shouldScroll) {
          console.log('ChatContent: 触发滚动到底部');
          this.scrollToBottom();
          this.$store.commit('chat/SET_SHOULD_SCROLL', false);
        }
      }
    );
    
    // 添加点击事件监听器
    document.addEventListener("click", this.hideFloatWindow);
  },

  beforeDestroy() {
    // 销毁WebSocket事件中心
    this.destroyWebSocketEventCenter();
    
    // 移除Vuex监听器
    if (this.unwatchScroll) {
      this.unwatchScroll();
    }
    
    // 移除点击事件监听器
    document.removeEventListener("click", this.hideFloatWindow);
  }
};
</script>

<style scoped>
.chat-content {
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;
}

/* 确保滚动容器有正确的高度 */
#content {
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;
}
</style>